package cn.practice.chat.security;

import cn.practice.chat.exception.CustomException;
import cn.practice.chat.lang.Const;
import cn.practice.chat.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @description 验证码过滤器
 **/
@Slf4j
@Component
public class CaptchaFilter extends OncePerRequestFilter {


    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private LoginFailureHanlder loginFailureHandler;

    @Override
    protected void doFilterInternal(
            HttpServletRequest request,
            HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {

        String url = request.getRequestURI();

        if(("/login".equals(url) || "/regist".equals(url)) && request.getMethod().equals("POST") ){
            try{
                //校验验证码
                log.info("开始对验证码校验。。。。");
                validate(request);
                //如果不正确，就跳转到认证失败处理器
            }catch (CustomException e){
                //交给失败的处理器（认证失败处理器）
                loginFailureHandler.onAuthenticationFailure(request,response,e);
            }
        }
        filterChain.doFilter(request,response);
    }
    //校验逻辑
    private void validate(HttpServletRequest request) {
        String code = request.getParameter("code");
        String key = request.getParameter("token");
        String url = request.getRequestURI();
        if("/regist".equals(url)){
            code = request.getHeader("code");
            key = request.getHeader("token");
        }
        log.info("验证码code={},token={}", code, key);
        if(StringUtils.isBlank(code) || StringUtils.isBlank(key)){
            throw new CustomException("验证码错误");
        }
        if(!code.equals(redisUtil.hget(Const.CAPTCHA_KEY, key))){
            log.error("比对验证码结果：false");
            throw new CustomException("验证码错误");
        }
        //一次性使用
        redisUtil.hdel(Const.CAPTCHA_KEY, key);
    }
}
